﻿using System;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;
using Jd.Api.Request;
using Jd.Api;

namespace JingDong.Open.Platform
{
    public class GetOrderInfo : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            try
            {
                var request = args.Length > 0 ? args[0] as JObject : dataset.GetJsonObject("request");
                var dbOrderInfo = dataset.GetJsonObjectValue("orderinfo");
                var constant = dataset.GetJsonObject("constant");
                var jingdongAPIConfig = constant.GetJsonObject("jingdongAPIConfig");

                string optionalFields = constant.GetJsonObjectStringValue("optional_fields");
                string order_id = request.GetJsonObjectStringValue("order_id");
                string eShopCode = request.GetJsonObjectStringValue("token");
                string url = jingdongAPIConfig.GetJsonObjectStringValue("url");
                string appKey = jingdongAPIConfig.GetJsonObjectStringValue("app_key");
                string appSecret = jingdongAPIConfig.GetJsonObjectStringValue("app_secret");

                if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
                    throw new BaseException("@0002", "");

                if (string.IsNullOrWhiteSpace(eShopCode))
                    throw new BaseException("@3002", "");

                if (string.IsNullOrWhiteSpace(order_id))
                    throw new BaseException("@3003", "");

                string orderId = order_id;

                string accessToken = GetAccessToken.GetToken(eShopCode, constant);

                JObject orderInfo = null;
                if (dbOrderInfo != null && dbOrderInfo.Type == JTokenType.Array && dbOrderInfo.HasValues && dbOrderInfo[0] is JObject)
                {
                    orderInfo = JSONHelper.JsonToJObject((dbOrderInfo[0] as JObject).GetJsonObjectStringValue("responseJson"));
                }

                string errMsg = null;
                if (orderInfo == null)
                {
                    var client = new DefaultJdClient(url, appKey, appSecret);

                    PopOrderGetRequest orderRequest = new PopOrderGetRequest();
                    orderRequest.orderId = orderId;
                    orderRequest.optionalFields = optionalFields;
                    var orderResponse = client.Execute(orderRequest, accessToken, DateTime.Now.ToLocalTime());

                    if (!orderResponse.IsError)
                    {
                        var orderData = JSONHelper.JsonToJObject(orderResponse.Body);
                        orderInfo = orderData.GetJsonObject("jingdong_pop_order_get_responce").GetJsonObject("orderDetailInfo").GetJsonObject("orderInfo");
                        if (orderInfo == null)
                            errMsg = orderResponse.orderDetailInfo?.apiResult?.chineseErrCode;
                    }
                    else
                    {
                        LogHelper.Info("jingdong_pop_order_get_responce error:");
                        LogHelper.Info(orderResponse);
                        errMsg = orderResponse.ErrMsg;
                    }
                }

                if (orderInfo == null)
                    throw ExceptionHelper.GenException("@3004", errMsg); ;

                return orderInfo;
            }
            catch(BaseException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                LogHelper.Info("GetOrderInfo fail: " + ex.Message);
                throw new Exception("@3001");
            }
        }
    }
}
